package com.xuzhiguang.light.gateway.common.utils;

import com.google.gson.Gson;
import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter;

import java.util.Properties;

/**
 * @author xuzhiguang
 */
public class PropertiesUtils {


    public static<T> T toBean(Properties properties, Class<T> clz) {
        return toBean(properties, clz, null);
    }

    public static <T> T toBean(Properties properties, Class<T> clz, String prefix) {
        if (prefix == null) {
            prefix = "";
        } else if (!prefix.isEmpty() && !prefix.endsWith(".")) {
            prefix += ".";
        }

        final String prefixStr = prefix;
        Properties newProperties = new Properties();

        properties.forEach((o, o2) -> {
            String key = o.toString();
            if (key.startsWith(prefixStr)) {
                newProperties.put(key.substring(prefixStr.length()), o2);
            }
        });

        String json = new PropertiesToJsonConverter().convertToJson(newProperties);
        Gson gson = new Gson();

        return gson.fromJson(json, clz);
    }

}
